package message

import (
	"car-thirdparty-api/internal/consts"
	"car-thirdparty-api/internal/dao"
	"car-thirdparty-api/internal/model"
	"car-thirdparty-api/internal/model/entity"
	"context"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
)

func (c *LogicV1) SendMessage(ctx context.Context, req *model.MessageSendReq) (res *model.MessageSendRes, err error) {
	dictData, err := c.selectDictData(ctx, "biz_msg_conf")
	if err != nil {
		g.Log().Error(ctx, "查询字典数据失败, ", err)
		return nil, err
	}
	if dictData == nil {
		g.Log().Error(ctx, "查询字典数据失败, ", err)
		return nil, gerror.NewCode(gcode.CodeNotFound)
	}
	appkey := ""
	appsecret := ""
	fullTextSmsUrl := ""
	signature := ""
	for _, datum := range dictData {
		switch datum.DictValue {
		case "appkey":
			appkey = datum.DictLabel
		case "appsecret":
			appsecret = datum.DictLabel
		case "FullTextSmsUrl":
			fullTextSmsUrl = datum.DictLabel
		case "signature":
			signature = datum.DictLabel
		}
	}
	if appkey == "" || appsecret == "" || fullTextSmsUrl == "" || signature == "" {
		g.Log().Error(ctx, "参数配置错误")
		return nil, gerror.NewCode(gcode.CodeValidationFailed)
	}
	msgData := g.Map{
		"appkey":    appkey,
		"appsecret": appsecret,
		"phone":     req.Phone,
		"content":   signature + req.Content,
	}
	//g.Log().Debug(ctx, "发送短信参数为：", msgData)
	// 将msgData转成json字符串
	msgDataJson, err := gjson.EncodeString(msgData)
	g.Log().Debug(ctx, "发送短信参数为：", msgDataJson)

	insertData := entity.MessageRecord{
		Phone:      req.Phone,
		Plate:      req.Plate,
		Context:    req.Content,
		Type:       req.MsgType,
		Status:     consts.SUCCESS,
		SendTime:   gtime.Now(),
		CreateTime: gtime.Now(),
		UpdateTime: gtime.Now(),
	}

	// 试用 g.Client的Post方法发送请求，并处理返回结果json对象
	resData := "{}"
	jsonResp := gjson.New(resData)
	resp, err := g.Client().Post(ctx, fullTextSmsUrl, msgDataJson)
	if err != nil {
		insertData.Status = consts.FAIL
		g.Log().Error(ctx, "发送短信失败, ", err)
		goto end
	}
	defer resp.Close()
	resData = resp.ReadAllString()
	g.Log().Debug(ctx, "发送短信返回结果为：", resData)

	jsonResp, err = gjson.DecodeToJson(resData)
	if err != nil {
		insertData.Status = consts.FAIL
		goto end
	}
	if jsonResp.Get("code").Int() != 0 {
		insertData.Status = consts.FAIL
		g.Log().Error(ctx, "发送短信失败, ", jsonResp.Get("msg"))
		err = gerror.NewCode(gcode.CodeInternalError)
	}

end:
	// 记录发送日志
	_, err = dao.MessageRecord.Ctx(ctx).Data(insertData).Insert()

	g.Log().Debug(ctx, "发送短信成功")

	return
}

func (c *LogicV1) selectDictData(ctx context.Context, dictType string) (dictData []*entity.SysDictData, err error) {
	dictData = make([]*entity.SysDictData, 0)
	err = dao.SysDictData.Ctx(ctx).Where("dict_type = ?", dictType).Scan(&dictData)
	if err != nil {
		g.Log().Error(ctx, "查询字典数据失败, ", err)
		return nil, err
	}

	return
}
